package com.heima.freemarker.web;

import com.heima.freemarker.pojo.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class FreemarkerController {


    @Autowired
    Configuration configuration;

    @GetMapping("/demo")
    public String demo(Model model){
        model.addAttribute("name", "张三");
        
//        Map<String, Object> stu = new HashMap<>();
//        stu.put("name", "hello");
//        stu.put("age", 18);

        Student student = new Student("hello", 18);

        model.addAttribute("stu", student);
        // 模板的名称
        return "01-basic";
    }

    @GetMapping("/demo2")
    public void demo(Model model, HttpServletResponse response) throws Exception{
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> stu = new HashMap<>();
        stu.put("name", "hello");
        stu.put("age", 18);

        data.put("name", "张三");
        data.put("stu", stu);

        response.setHeader("Content-Type", "text/html;charset=utf-8");
        // 模板 + 数据 = html
        Template template = configuration.getTemplate("01-basic.ftl");
        template.process(data, response.getWriter());
    }

    @GetMapping("/demo3")
    public void demo3(Model model, HttpServletResponse response) throws Exception{
        Map<String, Object> data = new HashMap<>();

        Map<String, Object> stu = new HashMap<>();
        stu.put("name", "hello");
        stu.put("age", 18);

        data.put("name", "张三");
        data.put("stu", stu);

        response.setHeader("Content-Type", "text/html;charset=utf-8");

        StringWriter stringWriter = new StringWriter();
        // 模板 + 数据 = html
        Template template = configuration.getTemplate("01-basic.ftl");
        template.process(data, stringWriter);

        String html = stringWriter.toString();
        log.info(html);

        response.getOutputStream().write(html.getBytes());

    }

}